package org.vt.eldercare.dummy;

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import gnu.io.SerialPortEventListener;

public class SerialDummyAP implements Runnable {

	private SerialPortEventListener listener;

	private PipedInputStream in = new PipedInputStream();

	private PipedOutputStream out;

	public SerialDummyAP() {
		try {
			out = new PipedOutputStream(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setSerialPortEventListener(SerialPortEventListener listener) {
		this.listener = listener;
	}

	public InputStream getInputStream() {
		return in;
	}

	public void run() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				while (true) {
					byte[] toWrite = { 0, (byte) (255 * Math.random()),
							(byte) (100 * Math.random()),
							(byte) (20 * Math.random()),
							(byte) (255 * Math.random()),
							(byte) (25 * Math.random()),
							(byte) (155 * Math.random()),
							(byte) (255 * Math.random()),
							(byte) (155 * Math.random()),
							(byte) (5 * Math.random()),
							(byte) (255 * Math.random()), 0, '\n' };
					try {
						out.write(toWrite);
						out.flush();
						toWrite[0] = 32;
						toWrite[2] = 0;
						out.write(toWrite);
						out.flush();
						toWrite[0] = 64;
						toWrite[3] = 0;
						out.write(toWrite);
						out.flush();
						toWrite[0] = 96;
						toWrite[1] = 0;
						out.write(toWrite);
						out.flush();
						toWrite[0] = (byte) (32*4);
						toWrite[2] = 0;
						out.write(toWrite);
						out.flush();
						toWrite[0] = (byte) (32*5);
						toWrite[3] = 0;
						out.write(toWrite);
						out.flush();
						toWrite[0] = (byte) (32*6);
						toWrite[1] = 0;
						out.write(toWrite);
						out.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		t.start();
		while (true) {
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			listener.serialEvent(null);
		}
	}
}
